package com.qdc.datacenters.listener;

import com.alibaba.fastjson.JSONObject;
import com.qdc.datacenters.client.ChatMsgAuditClient;
import com.qdc.datacenters.config.redis.RedisService;
import com.qdc.datacenters.domain.entity.ChatContactMsgExtend;
import com.qdc.datacenters.domain.entity.CorpCustomer;
import com.qdc.datacenters.domain.entity.CorpPermitUser;
import com.qdc.datacenters.domain.queue.ChatMsgQueue;
import com.qdc.datacenters.domain.vo.group.CorpGroupVo;
import com.qdc.datacenters.event.QwMsgExtendEvent;
import com.qdc.datacenters.service.IChatContactMsgExtendService;
import com.qdc.datacenters.service.ICorpCustomerService;
import com.qdc.datacenters.service.ICorpGroupService;
import com.qdc.datacenters.service.ICorpPermitUserService;
import com.qdc.datacenters.service.impl.ThreadFactoryImpl;
import com.qdc.datacenters.utils.ThreadUtils;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * @author danmo
 * @date 2024-03-12 15:15
 **/
@Slf4j
@AllArgsConstructor
@Component
public class QwMsgExtendListener implements ApplicationListener<QwMsgExtendEvent> {

    private final ICorpPermitUserService iCorpPermitUserService;
    private final ICorpCustomerService iCorpCustomerService;
    private final ICorpGroupService iCorpGroupService;
    private final RedisService redisService;
    private final IChatContactMsgExtendService iChatContactMsgExtendService;

    @Resource
    private ChatMsgAuditClient auditClient;
    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 10L, MILLISECONDS, new ArrayBlockingQueue<>(1024), new ThreadFactoryImpl("extendPullThread_"));

    @Override
    public void onApplicationEvent(QwMsgExtendEvent extendEvent) {
        executor.execute(() -> {
            ChatMsgQueue queue = (ChatMsgQueue) extendEvent.getSource();
            try {
                if (Objects.isNull(queue) || Objects.isNull(queue.getMsg())) {
                    return;
                }
                log.info("获取到会话拓展消息 query:{}", JSONObject.toJSONString(queue));
                ChatContactMsgExtend contactMsgExtend = new ChatContactMsgExtend();
                contactMsgExtend.setMsgId(queue.getMsg().getId());
                //判断单聊群聊
                if (Objects.equals(1, queue.getMsg().getChatType())) {
                    setCustomerAndUserInfo(queue.getMsg().getFromId(), 1, contactMsgExtend);
                    setCustomerAndUserInfo(queue.getMsg().getToList(), 2, contactMsgExtend);
                } else {
                    //若果是内部群则从企微获取内部群信息
                    if (!queue.getMsg().getMsgId().contains("external")) {
                        //设置内部群信息
                        setInternalGroupChatInfo(queue.getMsg().getRoomId(), contactMsgExtend);
                    } else {
                        //外部群信息
                        setExternalGroupChatInfo(queue.getMsg().getRoomId(), contactMsgExtend);
                    }
                }
                iChatContactMsgExtendService.save(contactMsgExtend);
            } catch (Exception e) {
                log.error("会话拓展处理异常 queue:{},msg:{}",JSONObject.toJSONString(queue),e.getMessage(),e);
            }
        });
    }

    private void setCustomerAndUserInfo(String customerId, Integer type, ChatContactMsgExtend contactMsg) {
        if (customerId.startsWith("wm") || customerId.startsWith("wo")) {
            CorpCustomer corpCustomer = iCorpCustomerService.getByExternalUserId(customerId);
            if (Objects.nonNull(corpCustomer)) {
                if (type == 1) {
                    contactMsg.setFromSex(corpCustomer.getGender());
                    contactMsg.setFromAvatar(corpCustomer.getAvatar());
                    contactMsg.setFormName(corpCustomer.getName());
                } else if (type == 2) {
                    contactMsg.setReceiverSex(corpCustomer.getGender());
                    contactMsg.setReceiverAvatar(corpCustomer.getAvatar());
                    contactMsg.setReceiverName(corpCustomer.getName());
                }
            }
        } else {
            CorpPermitUser permitUser = iCorpPermitUserService.getByCorpUserId(customerId);
            if (Objects.nonNull(permitUser)) {
                if (type == 1) {
                    contactMsg.setFromSex(permitUser.getGender());
                    contactMsg.setFromAvatar(permitUser.getAvatar());
                    contactMsg.setFormName(permitUser.getCorpUserName());
                } else if (type == 2) {
                    contactMsg.setFromSex(permitUser.getGender());
                    contactMsg.setReceiverAvatar(permitUser.getAvatar());
                    contactMsg.setReceiverName(permitUser.getCorpUserName());
                }
            }
        }
    }


    private void setInternalGroupChatInfo(String roomId, ChatContactMsgExtend contactMsgExtend) {
        CorpGroupVo corpGroupVo = iCorpGroupService.getByChatId(roomId, 2);
        if (Objects.nonNull(corpGroupVo)) {
            contactMsgExtend.setRoomId(roomId);
            contactMsgExtend.setRoomName(corpGroupVo.getGroupName());
        }
    }

    private void setExternalGroupChatInfo(String roomId, ChatContactMsgExtend contactMsgExtend) {
        CorpGroupVo corpGroupVo = iCorpGroupService.getByChatId(roomId);
        if (Objects.nonNull(corpGroupVo)) {
            contactMsgExtend.setRoomId(roomId);
            contactMsgExtend.setRoomName(corpGroupVo.getGroupName());
        }
    }

    @PreDestroy
    public void shutdown() {
        log.info("聊天信息扩展线程池开始注销");
        ThreadUtils.shutdownAndAwaitTermination(executor);
    }
}
